package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.ShowServiceEnterpriseDto;
import com.aiti.lulian.entity.ShowServiceEnterprise;
import com.aiti.lulian.entity.excel.ShowServiceEnterpriseExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.ShowServiceEnterpriseService;
import com.aiti.lulian.vo.EmployeeOpportunityCountVo;
import com.aiti.lulian.vo.ShowServiceEnterpriseVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务企业 前端控制器
 * </p>
 *
 * @author 
 * @since 2025-06-13
 */
@RestController
@RequestMapping("/serviceEnterprise")
public class ShowServiceEnterpriseController extends WebController {

    @Autowired
    private ShowServiceEnterpriseService serviceEnterpriseService;

    @GetMapping("/page")
    public Message page(ShowServiceEnterpriseDto dto){
        Integer pageSize = dto.getPageSize();
        Integer pageNum = dto.getPageNum();
        Page<EmployeeOpportunityCountVo> page = this.startPage(pageNum, pageSize);
        List<ShowServiceEnterpriseVo> showServiceEnterpriseVos = serviceEnterpriseService.serviceEnterprisePage(page, dto);
        return Message.success(getPageResult(showServiceEnterpriseVos,pageNum, pageSize, (int)page.getTotal()));
    }

    @GetMapping("/detail")
    public Message detail(ShowServiceEnterpriseDto dto){
        ShowServiceEnterprise entity = serviceEnterpriseService.getById(dto.getBaseId());
        return Message.success(entity);
    }

    @DeleteMapping
    public Message delete(ShowServiceEnterpriseDto dto){
        String baseId = dto.getBaseId();
        if(StrUtil.isNotBlank(baseId)){
            serviceEnterpriseService.removeById(baseId);
            return Message.success();
        }else{
            return Message.fail("传参有误");
        }

    }

    @PostMapping
    public Message insert(@RequestBody ShowServiceEnterprise entity){
        entity.setCreator(findUserId());
        serviceEnterpriseService.save(entity);
        return Message.success();
    }

    @PutMapping
    public Message update(@RequestBody ShowServiceEnterprise entity){
        entity.setUpdateBy(findUserId());
        return serviceEnterpriseService.updateServiceEnterprise(entity);
    }

    @ApiOperation("下载服务企业导入模版")
    @GetMapping("/importTemplate/download")
    public void downloadServiceEnterpriseImportTemplate(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            // 设置文件路径
//            String filePath = "/Volumes/WorkDisk/ShanDongZhiZao/workspace/template/工信门户-服务企业导入模版.xlsx";
            String filePath = "/home/services/template/工信门户-服务企业导入模版.xlsx";
//            String filePath = "C:\\Users\\Administrator\\Desktop\\工信门户-服务企业导入模版.xlsx;
            File downloadFile = new File(filePath);

            // 设置文件名（响应头中的推荐文件名）
            String fileName = "服务企业导入模版.xlsx";

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 设置文件大小
            response.setContentLength((int) downloadFile.length());

            // 通过文件输入流读取文件内容
            fileInputStream = new FileInputStream(downloadFile);

            // 通过ServletOutputStream将文件内容写入HTTP响应
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            logger.error("下载服务企业导入模版异常：===》" + e);
        }
    }

    @ApiOperation("批量导入服务企业")
    @PostMapping("/importBatch")
    public Message importServiceEnterpriseBatch(@RequestPart("file") MultipartFile file) {
        try {
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            if (file == null) {
                return Fail("请上传文件");
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            if (! ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)
                    && originalFilename != null && originalFilename.endsWith(".xlsx"))) {
                return Fail("请上传xlsx格式的文件");
            }
            return serviceEnterpriseService.importBatch(file, userId);
        } catch (Exception e) {
            logger.error("导入异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("导出服务企业列表")
    @GetMapping("/list/export")
    public Message exportServiceEnterpriseList(HttpServletResponse response, ShowServiceEnterpriseDto dto) {
        try {
            List<ShowServiceEnterpriseVo> showServiceEnterpriseVos = serviceEnterpriseService.serviceEnterprisePage(null, dto);
            List<ShowServiceEnterpriseExport> serviceEnterpriseExportList = showServiceEnterpriseVos.stream().map(i -> {
                ShowServiceEnterpriseExport serviceEnterpriseExport = new ShowServiceEnterpriseExport();
                BeanUtils.copyProperties(i, serviceEnterpriseExport);
                return serviceEnterpriseExport;
            }).collect(Collectors.toList());

            // 设置响应头，确保浏览器以下载方式处理文件
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置文件名，注意需要对中文进行 URL 编码
            String fileName = URLEncoder.encode("服务企业列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入数据到输出流
            OutputStream outputStream =  response.getOutputStream();
            EasyExcel.write(outputStream, ShowServiceEnterpriseExport.class)
                    .sheet("服务企业列表")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(serviceEnterpriseExportList);

            // 关闭流资源
            if (outputStream != null) {
                outputStream.close();
            }

            return Message.success();
        } catch (Exception e) {
            logger.error("导出异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }
}
